package com.shell.config;

import com.shell.scheduler.JobStateListener;
import com.shell.scheduler.JobTraceListener;
import com.shell.scheduler.SchedulerBootstrap;
import java.util.Properties;
import javax.sql.DataSource;
import org.quartz.JobListener;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class SchedulerConfig {
	
	@Autowired
	private DataSource dataSource;

	@Bean({ "jobStateListener" })
	public JobStateListener getJobStateListener() {
		return new JobStateListener();
	}

	@Bean({ "jobTraceListener" })
	public JobTraceListener getJobTraceListener() {
		return new JobTraceListener();
	}

	@Bean(name = { "schedulerFactoryBean" }, autowire = Autowire.NO)
	public SchedulerFactoryBean getSchedulerFactoryBean() {
		SchedulerFactoryBean sfb = new SchedulerFactoryBean();
		sfb.setDataSource(this.dataSource);
		sfb.setGlobalJobListeners(new JobListener[] { getJobStateListener(), getJobTraceListener() });
		sfb.setApplicationContextSchedulerContextKey("applicationContext");
		Properties properties = new Properties();
		properties.setProperty("org.quartz.scheduler.instanceName", "CRMscheduler");
		properties.setProperty("org.quartz.scheduler.instanceId", "AUTO");
		properties.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
		properties.setProperty("org.quartz.threadPool.threadCount", "20");
		properties.setProperty("org.quartz.threadPool.threadPriority", "5");
		properties.setProperty("org.quartz.jobStore.misfireThreshold", "120000");
		properties.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
		properties.setProperty("org.quartz.jobStore.isClustered", "true");
		properties.setProperty("org.quartz.jobStore.clusterCheckinInterval", "15000");
		properties.setProperty("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
		properties.setProperty("org.quartz.jobStore.tablePrefix", "qrtz_");
		properties.setProperty("org.quartz.jobStore.dataSource", "qzDS");
		sfb.setQuartzProperties(properties);
		sfb.setOverwriteExistingJobs(true);
		sfb.setAutoStartup(false);
		return sfb;
	}

	@Bean
	public SchedulerBootstrap getSchedulerBootstrap() {
		return new SchedulerBootstrap();
	}
}
